package com.boot2.core.conf;

import com.boot2.core.utils.ThreadPoolTaskExecutorUtil;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;

/**
 * @author zhangweilin
 * @Description: spring 异步方法线程池（默认的使用的池SimpleAsyncTaskExecutor：不是真的线程池，这个类不重用线程，每次调用都会创建一个新的线程。 ）
 * @date 2019/12/31
 */
@Configuration
@Component
@CommonsLog
public class AsyncTaskExecutorConf extends AsyncConfigurerSupport {


    /**
     * 自定义异步线程池
     *
     * @return
     */
//    @Bean
//    public AsyncTaskExecutor asyncTaskExecutor() {
//        ThreadPoolTaskExecutor executor = ThreadPoolTaskExecutorUtil.createThreadPoolTaskExecutor(0.7);
//        executor.setThreadNamePrefix("async_task_executor_");
//        // 设置拒绝策略
//        executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
//            @Override
//            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
//                log.error("异步执行异常了, r: "+r);
//                executor.submit(r);
//            }
//        });
//        // 使用预定义的异常处理类
//        // executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//
//        return executor;
//    }
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = ThreadPoolTaskExecutorUtil.createThreadPoolTaskExecutor(0.7);
        executor.setThreadNamePrefix("async_task_executor_");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler((r, executor1) -> {
            log.error("异步执行异常了, r: " + r);
            executor1.submit(r);
        });
        // 使用预定义的异常处理类
        // executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        return executor;
    }


}
